<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>生产工艺模板列表</title>
    <!-- 引入 Element UI 的样式 -->
    <!-- <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css" /> -->
    <link rel="stylesheet" href="../../assets/css/element-ui.css" />
    <link rel="stylesheet" href="../../assets/css/styles.css" />
    <script src="../../assets/js/cdn.js"></script>
    <link rel="stylesheet" href="../../assets/fontawesome-free-6.7.2-web/css/all.min.css" />
  </head>
  <body>
    <div id="app">
      <lx-header slot="header" v-on:toggle="isToggle = !isToggle"></lx-header>
      <div class="main-content">
        <div class="content" style="width: 100%">

<!--          <el-row :gutter="10" class="mb8">-->
<!--                <el-col :span="1.5">-->
<!--                    <el-button type="primary" plain size="mini" @click="handleAdd">新增</el-button>-->
<!--                </el-col>-->
<!--            </el-row>-->

          <div class="center-grid mb-20">
            <el-table v-loading="loading" :data="tableData">
                <el-table-column v-for="(item, index) in tableColumnData" :key="index" :label="item.fieldName" min-width="150" :width="item.width">
                    <template slot-scope="scope">
                      <template> {{ scope.row[item.fieldApi] }} </template>
                    </template>
                  </el-table-column>
                <el-table-column label="操作" align="center" :resizable="false" :show-overflow-tooltip="false" width="210" fixed="right">
                    <template slot-scope="scope">
                        <el-button size="mini" type="text"  @click="detailView(scope.row)">详情</el-button>
<!--                        <el-button size="mini" type="text"  @click="handleUpdate(scope.row)">修改</el-button>-->
                        <el-button size="mini" type="text"  @click="processesSetting(scope.row)">配置工序</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination
                v-show="total>0"
                :total="total"
                :current-page.sync="queryParams.pageNum"
                :page-size.sync="queryParams.pageSize"
                @current-change="getList"
            />
          </div>
        </div>
      </div>

        <!-- 添加或修改对话框 -->
        <el-dialog :title="title" :visible.sync="open" :fullscreen="true" width="800px" append-to-body>
            <el-form ref="form" :inline="true" :model="form" :rules="rules" label-width="120px">
                <el-form-item label="模板名称" prop="ptName">
                    <el-input v-model="form.ptName" placeholder="请输入模板名称" />
                </el-form-item>
                <el-form-item label="车平台" prop="carPlatformCode">
                    <el-select v-model="form.carPlatformCode" placeholder="请选择车平台" :disabled="submitFlag === 1" @change="getCarModelList()">
                        <el-option v-for="item in carPlatformOptions" :key="item.carPlatformCode" :label="item.carPlatformCode+'-'+item.carPlatformName" :value="item.carPlatformCode" />
                    </el-select>
                </el-form-item>
                <el-form-item label="车型号" prop="carModelCode">
                    <el-select v-model="form.carModelCode" placeholder="请选择车型号" :disabled="submitFlag === 1">
                        <el-option v-for="item in carModelOptions" :key="item.carModelCode" :label="item.carModelCode+'-'+item.carModelName" :value="item.carModelCode" />
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <el-dialog title="配置工序" :visible.sync="settingOpen" :fullscreen="true" width="800px" append-to-body>
            <div style="display: inline-flex;width: 100%;">
                <div style="width: 40%;margin-left: 5%">
                    <h2>可选工序</h2>
                    <el-table ref="optionsObjTable" v-loading="loading" :data="optionsObj" :height="450">
                        <el-table-column label="工序名称" prop="puName" min-width="150">
                            <template slot-scope="scope">
                                <template> {{ scope.row["puCode"]+'-'+scope.row["puName"] }} </template>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" align="center" :resizable="false" :show-overflow-tooltip="false" width="220" fixed="right">
                            <template slot-scope="scope">
                                <el-button size="mini" type="text"  @click="saveSetting(scope.row,index)">选择</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div style="width: 40%;margin-left: 10%">
                    <h2>已选工序</h2>
                    <el-table ref="basePtPusTable" v-loading="loading"
                              row-key="puCode"
                              :data="basePtPus"
                              class="dragging-table"
                              :height="450">
                        <el-table-column label="工序名称" prop="puName" min-width="150">
                            <template slot-scope="scope">
                                <template> {{ scope.row["puName"] }} </template>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" align="center" :resizable="false" :show-overflow-tooltip="false" width="220" fixed="right">
                            <template slot-scope="scope">
                                <el-button size="mini" type="text"  @click="moveToTop(scope.row,scope.$index)">上移</el-button>
                                <el-button size="mini" type="text"  @click="moveToBottom(scope.row,scope.$index)">下移</el-button>
                                <el-button size="mini" type="text"  @click="delSetting(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                        <!--<el-table-column label="排序" prop="sort">
                            <template slot-scope="scope">
                                <template> {{ scope.row["sort"] }} </template>
                            </template>
                        </el-table-column>-->
                    </el-table>

                </div>
            </div>
        </el-dialog>

    </div>
    <script src="../../assets/js/constant.js"></script>
    <script src="../../assets/js/utils.js"></script>
    <script src="../../assets/js/auth.js"></script>
    <script src="../../assets/js/axios.min.js"></script>
    <script src="../../assets/js/Sortable.min.js"></script>
    <!-- 引入 Vue.js -->
    <script src="../../assets/js/vue.js"></script>
    <script src="../../assets/js/element-ui.js"></script>
    <script type="module">
      import LxHeader from '../../pages/components/LxHeader/index.js'
      Vue.component('lx-header', LxHeader)
      checkAuthentication(2)
      new Vue({
        el: '#app',
        components: {},
        data() {
         return {
            currentUser: JSON.parse(localStorage.getItem('currentUser')) || {},
            userMenuList: JSON.parse(localStorage.getItem('userMenuList')) || [],
            businessCenters: [
                { name: '订单中心', path: '../index.html' },
                { name: '用户中心', path: '#' },
                { name: '产品中心', path: '#' },
                { name: '库存中心', path: '#' },
                { name: '财务中心', path: '#' },
                { name: '数据中心', path: '#' },
                { name: '系统中心', path: '#' },
                { name: '消息中心', path: '#' }
            ],
            queryParams: {
              pageNo: 1,
              pageSize: 10,
              puCode: '',
              puName: ''
            },
            total: 0,
            tableData: [],
            tableColumnData: [
              // {
              //   fieldName: '生产工艺模板',
              //   fieldApi: 'ptName'
              // },
              {
                fieldName: '车平台',
                fieldApi: 'carPlatformName'
              },
              {
                fieldName: '车型号',
                fieldApi: 'carModelName'
              },
              {
                fieldName: '创建时间',
                fieldApi: 'createTime'
              },
              {
                fieldName: '创建人',
                fieldApi: 'createBy'
              }
            ],
            // 遮罩层
            loading: true,
            allOptionsObj: [],
            optionsObj: [],
            selectedPuIds:[],
            basePtPus:[],
            carPlatformOptions:[],
            carModelOptions:[],
            // 选中数组
            ptCodes: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            settingOpen: false,
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                carModelCode: [{ required: true, message: '请选择车型号', trigger: 'blur' }],
            },
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            submitFlag: 0,
            request_host: request_host,
            pageSizes: pageSizes,
            multipleSelection: []
          }
        },
        created() {
            this.getOptions()
            this.getCarPlatformList()
            this.init()
        },
        methods: {
          exit,
          init() {
            this.getList()
          },
          getList() {
            this.loading = true
            try {
              axios.get(`${this.request_host}/system/pt/list`,{ params: this.queryParams }).then((response) => {
                if (response.status == 200) {
                  this.tableData = response.data.rows
                  this.total = response.data.total
                  this.loading = false
                }
              })
            } catch (error) {
              console.error('请求失败:', error)
            }
          },
          getOptions() {
                axios.get(`${this.request_host}/system/pu/allList`).then((response) => {
                    if (response.status == 200) {
                        this.allOptionsObj = response.data.data
                        this.optionsObj = response.data.data
                        /*response.data.data.forEach(element => {
                            this.optionsObj.push({"key":element.puCode,"label":element.puCode+"-"+element.puName})
                        });*/
                    }
                })
            },
            getCarPlatformList() {
                axios.get(`${this.request_host}/system/platform/allList`).then((response) => {
                    if (response.status == 200) {
                        response.data.data.forEach(element => {
                            this.carPlatformOptions.push(element)
                        });
                    }
                })
            },
            getCarModelList() {
              console.log(this.form)
                this.carModelOptions = []
                axios.get(`${this.request_host}/system/model/allList?carPlatformCode=${this.form.carPlatformCode}`).then((response) => {
                    if (response.status == 200) {
                        response.data.data.forEach(element => {
                            var item = {"carModelCode": element.carModelCode,"carModelName":element.carModelName}
                            this.carModelOptions.push(item)
                        });
                    }
                })
            },
          /** 提交按钮 */
          submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    this.form.basePtPus = this.basePtPus
                    if (this.submitFlag == 0){
                      this.form.ptCode = this.form.carModelCode;
                      const ptCode = this.form.ptCode
                        // 新增
                        axios.post(`${this.request_host}/system/pt`, this.form)
                            .then(response => {
                                if (response.data.code == 200){
                                    this.$message.success("提交成功")
                                    this.cancel();
                                    this.getList()
                                    const params = `ptCode=`+ptCode;
                                    const url = `pt_item.html?${params}`;
                                    window.open(url, '_blank');
                                }else {
                                    this.$message.error(response.data.msg)
                                }

                        })
                    }else{
                        this.form.ptCode = this.form.carModelCode;
                        const ptCode = this.form.ptCode
                        //修改提交
                        axios.put(`${this.request_host}/system/pt`, this.form)
                            .then(response => {
                                if (response.data.code == 200){
                                    this.$message.success("提交成功")
                                    this.cancel();
                                    this.getList();
                                    const params = `ptCode=`+ptCode;
                                    const url = `pt_item.html?${params}`;
                                    window.open(url, '_blank');
                                }else {
                                    this.$message.error(response.data.msg)
                                }

                        })
                    }

                }
            })
        },
        /** 保存配置配制工序 */
        saveSetting(row) {
            this.selectedPuIds.push(row.puCode)
            this.basePtPus.push({"puCode":row.puCode,"puName":row.puCode+"-"+row.puName,"sort":this.basePtPus.length+1})
            this.optionsObj = this.optionsObj.filter(item => item.puCode !== row.puCode);
            this.form.basePtPus = this.basePtPus
            this.form.ptCode = this.form.ptCode.toUpperCase();
            // 新增
            axios.post(`${this.request_host}/system/pt/saveSetting`, this.form)
                .then(response => {
                    if (response.data.code === 200){
                        //window.location.reload()
                    }else {
                        this.$message.error(response.data.msg)
                    }

                })
        },
        delSetting(row) {
            this.basePtPus = this.basePtPus.filter(item => item.puCode !== row.puCode);
            this.selectedPuIds = this.selectedPuIds.filter(item => item!== row.puCode);
            this.optionsObj = this.allOptionsObj.filter(item =>!this.selectedPuIds.includes(item.puCode));
            this.form.basePtPus = this.basePtPus
            this.form.ptCode = this.form.ptCode.toUpperCase();
            // 新增
            axios.post(`${this.request_host}/system/pt/saveSetting`, this.form)
                .then(response => {
                    if (response.data.code === 200){
                        //window.location.reload()
                    }else {
                        this.$message.error(response.data.msg)
                    }

                })
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.settingOpen = false
            this.form = {}
        },
          handleQuery() {
            this.getList()
          },
          resetQuery() {
            this.queryParams = {
              pageNo: 1,
              pageSize: 10,
              puCode: '',
              puName: ''
            }
          },
          /** 新增按钮操作 */
          handleAdd() {
            this.resetQuery()
            this.selectedPuIds = []
            this.basePtPus = []
            this.open = true
            this.form = {}
            this.submitFlag = 0
            this.title = "添加生产工艺模板"
          },
          /** 修改按钮操作 */
          handleUpdate(row) {
            this.resetQuery()
            const ptCode = row.ptCode || this.ptCodes[0]
            // 这里替换为实际的API调用
            axios.get(`${this.request_host}/system/pt/` + ptCode)
                .then(response => {
                    this.form = response.data.data
                    this.basePtPus = this.form.basePtPus || []
                    this.basePtPus.forEach(item=>{
                        this.selectedPuIds.push(item.puCode)
                    })
                    this.open = true
                    this.title = "修改生产工艺模板"
                    this.getCarModelList()
                });
            this.submitFlag = 1
          },
          /** 修改按钮操作 */
          processesSetting(row) {
              this.resetQuery()
              this.getCarModelList()
              const ptCode = row.ptCode || this.ptCodes[0]
              // 这里替换为实际的API调用
              axios.get(`${this.request_host}/system/pt/` + ptCode)
                  .then(response => {
                    this.selectedPuIds = []
                      this.form = response.data.data
                      if(this.form.basePtPus){
                          this.basePtPus = this.form.basePtPus
                          this.basePtPus.forEach(item=>{
                              this.selectedPuIds.push(item.puCode)
                          })
                      }else{
                          this.basePtPus = []
                      }
                      this.optionsObj = this.allOptionsObj.filter(item => !this.selectedPuIds.includes(item.puCode));
                      this.settingOpen = true
                      this.title = "修改生产工艺模板"
                  }).then(()=>{
                    const tableBody = document.querySelector('.dragging-table .el-table__body-wrapper tbody');
                    Sortable.create(tableBody, {
                        handle: '.el-table__row', // 使每行可拖动
                        onEnd: this.handleDragEnd // 拖动结束时处理排序
                    });
              });
          },
          handleDragEnd(evt) {
              const oldIndex = evt.oldIndex;
              const newIndex = evt.newIndex;
              //往后挪
              const arr = []
              if(oldIndex<newIndex){
                  for(let i=0;i<this.basePtPus.length;i++){
                      if(i<oldIndex || i>newIndex){
                          arr.push(this.basePtPus[i])
                      }else if(i>=oldIndex && i<newIndex){
                          arr.push(this.basePtPus[i+1])
                      }else if(i===newIndex){
                          arr.push(this.basePtPus[oldIndex])
                      }
                  }
              }else {
                  for(let i=0;i<this.basePtPus.length;i++){
                      if(i<newIndex || i>oldIndex){
                          arr.push(this.basePtPus[i])
                      }else if(i>newIndex && i<=oldIndex){
                          arr.push(this.basePtPus[i-1])
                      }else if(i===newIndex){
                          arr.push(this.basePtPus[oldIndex])
                      }
                  }
              }
              this.basePtPus = arr
              this.form.basePtPus = this.basePtPus
              this.form.ptCode = this.form.ptCode.toUpperCase();
              // 新增
              axios.post(`${this.request_host}/system/pt/saveSetting`, this.form)
                 .then(response => {
                      if (response.data.code === 200){
                          //window.location.reload()
                      }else{
                          this.$message.error(response.data.msg)
                      }
                 })
          },
            moveToTop(row,index) {
                if(index!==0){
                    this.basePtPus.splice(index-1,0,this.basePtPus.splice(index,1)[0])
                }
                this.form.basePtPus = this.basePtPus
                this.form.ptCode = this.form.ptCode.toUpperCase();
                // 新增
                axios.post(`${this.request_host}/system/pt/saveSetting`, this.form)
                    .then(response => {
                        if (response.data.code === 200){
                            //window.location.reload()
                        }else{
                            this.$message.error(response.data.msg)
                        }
                    })
            },
            moveToBottom(row,index) {
                if(index!==this.basePtPus.length-1){
                    this.basePtPus.splice(index+1,0,this.basePtPus.splice(index,1)[0])
                }
                this.form.basePtPus = this.basePtPus
                this.form.ptCode = this.form.ptCode.toUpperCase();
                // 新增
                axios.post(`${this.request_host}/system/pt/saveSetting`, this.form)
                    .then(response => {
                        if (response.data.code === 200){
                            //window.location.reload()
                        }else{
                            this.$message.error(response.data.msg)
                        }
                    })
            },
          // 分页数量切换
          handleSizeChange(val) {
            this.$set(this.queryParams, 'pageSize', val)
            this.getData()
          },
          // 当前页码切换
          handleCurrentChange(val) {
            this.$set(this.queryParams, 'pageNo', val)
            this.getData()
          },
          detailView(row) {
            const ptCode = row.ptCode;
            const params = `ptCode=${encodeURIComponent(ptCode)}`;
            const url = `pt_item.html?${params}`;
            window.open(url, '_blank');
          },
          openMenu(url) {
            window.open(url)
          },
        }
      })
    </script>
    <style>
      .el-table th.el-table__cell {
        background-color: #f2f2f2; /* 例如，设置为浅灰色 */
      }
      .mb8 {
        margin-bottom: 10px;
    }
    .el-transfer-panel{
        width: 250px;
        height: 450px;
    }
    .el-transfer-panel__list{
        height: 400px;
    }
    </style>
  </body>
</html>
